var express = require('express');
var router = express.Router();
const { v4: uuidv4 } = require('uuid');
const md5 = require('md5');

const Quert = require('../utils/db.js')

const {md5Screat,getToken} = require('../utils//config')

router.get('/', async function (req, res, next) {
    res.send('登录注册')
});
// 注册
router.post('/register', async (req, res, next) => {
    let { username, password, repwd } = req.body

    if (username == '' || password == '' || repwd == '') {
        next({
            "msg": "请传递必要参数",
            "status": 500
        })
        return
    }
    if (password !== repwd) {
        next({
            "msg": "两次密码不一致",
            "status": 500
        })
        return
    }

    let sql1 = `SELECT * FROM e_member WHERE username='${username}'`
    let res1 = await Quert(sql1)
    // res.send(res1.result.length)
    // return
    if (res1.result.length > 0) {
        next({
            "msg": "用户已被注册了",
            "status": 500
        })
        return
    }
    // uuidv4()
    createdate = Date.now()
    password = md5(password + md5Screat)

    let sql2 = `INSERT INTO e_member (  mid,username,password,createdate) VALUES ( '${uuidv4()}','${username}','${password}','${createdate}' )`
    let res2 = await Quert(sql2)

    if (res2.result.affectedRows > 0) {
        let data = {
            "msg": "注册成功",
            "status": 200
        }
        res.send(data)
    }

    // res.send(res1)
})

// 登录
router.post('/login', async (req, res, next) => {
    let { username, password } = req.body
    if (username == '' || password == '') {
        next({
            "msg": "请传递必要参数",
            "status": 500
        })
        return
    }

    password = md5(password + md5Screat)

    let sql = `SELECT * FROM e_member WHERE username='${username}' AND password='${password}'`
    let res1 = await Quert(sql)


    if (res1.result.length > 0) {
        let mid = res1.result[0].mid
        let username = res1.result[0].username
        let data = {
            username,
            mid
        }
        let token = getToken(data)
        res.send({
            "msg": "登录成功",
            "status": 500,
            result: {
                token,
                mid
            }
        })
        return
    } else {
        next({
            "msg": "请输入正确用户名和密码",
            "status": 500
        })
        return
    }
})
module.exports = router;
